//
//  TiJIaoDingDanViewController.m
//  Experss
//
//  Created by wmwMAC on 17/8/4.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "TiJIaoDingDanViewController.h"

#import "DingDanDetailLocationTableViewCell.h"
#import "DingDanDetailGoodsTableViewCell.h"
#import "DingDanDetailPriceTableViewCell.h"
#import "DingDanDetailPriceTableViewCell.h"
#import "DingDanDetailWordsTableViewCell.h"
#import "DingDanDetailNumberTableViewCell.h"
#import "DingDanPeiSongTableViewCell.h"
//#import "PeiSongStyleView.h"

#import "MyAddressViewController.h"//选择地址
#import "PayForViewController.h"//提交订单

#import "TiJiaoDingDanModle.h"
#import "GoodsMingXiViewController.h"

#import "DLPickerView.h"//选择配送方式
#import "HQPickerView.h"


static NSString *LocationIdentifier = @"DingDanDetailLocationTableViewCell";
static NSString *GoodsIdentifier = @"DingDanDetailGoodsTableViewCell";
static NSString *PriceIdentifier = @"DingDanDetailPriceTableViewCell";
static NSString *WordsIdentifier = @"DingDanDetailWordsTableViewCell";
static NSString *NumberIdentifier = @"DingDanDetailNumberTableViewCell";
static NSString *PeiSongIdentifier = @"DingDanPeiSongTableViewCell";



@interface TiJIaoDingDanViewController ()<UITableViewDelegate,UITableViewDataSource,DingDanDetailGoodsTableViewCellDelegate,HQPickerViewDelegate>
{
    NSMutableArray *desc_Arr;
    NSString *postWay;//配送方式
    
    UINib *_cellNib;
    NSInteger  indepathSection;
    NSInteger  indepathrow;
    
    
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *moneyLable;
@property (nonatomic, strong) NSMutableDictionary *addressDataDic;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableDictionary *dataDic;
@property (nonatomic, strong)HQPickerView *picker;

@property (nonatomic, strong)NSMutableArray *postWayArray;//配送方式数组

@end

@implementation TiJIaoDingDanViewController
-(void)setPopModle:(AddressListModel *)popModle{
    _popModle = popModle;
    if (_popModle) {
        
        self.addressDataDic = _popModle.mj_keyValues;
        
        [self GetOrderConfirmData22];//更改地址后重新获取运费以及其他信息
       
    }
}
// 获取订单详情
-(void)GetOrderConfirmData22{
    
    if (_dataArr) {
        [_dataArr removeAllObjects];
    }
    if (desc_Arr) {
        [desc_Arr removeAllObjects];
    }
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic;
    if (_buy_num.length>0) {
        parameDic = @{@"userid":saveDic[@"userid"],@"sku_id":_sku_id,@"buy_type":_buy_type,@"buy_num":_buy_num,@"address_id":_popModle.Id,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    }else{
        parameDic = @{@"userid":saveDic[@"userid"],@"sku_id":_sku_id,@"buy_type":_buy_type,@"address_id":_popModle.Id,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    }
    
    
    [HttpRequest postWithURLString:POST(Shop_OrderConfirm) parameters:parameDic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        _dataDic = [responseObject objectForKey:@"data"];
        [self chuliMoneyLable];
        
        if ([[responseObject objectForKey:@"ret"] integerValue] == 200) {
            
            NSArray *listarr = [[responseObject objectForKey:@"data"] objectForKey:@"list"];
            self.dataArr = [TiJiaoDingDanModle mj_objectArrayWithKeyValuesArray:listarr];
            
            self.addressDataDic = [[responseObject objectForKey:@"data"] objectForKey:@"address_data"];
            //先把运费保存一下
            if (_postWayArray ) {
                [_postWayArray removeAllObjects];
            }
            for (TiJiaoDingDanModle *model  in self.dataArr) {
                [_postWayArray addObject:model.delivery_price];
            }
        }else{
            [MBProgressHUD showText:[responseObject objectForKey:@"msg"]];
        }
        
        for (NSInteger i = 0; i<self.dataArr.count; i++) {
            [desc_Arr addObject:@""];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
}





- (void)viewDidLoad {
    [super viewDidLoad];
    
    postWay = @"自提:¥0";
    self.view.backgroundColor = BaseColor;
    self.navigationItem.title = @"提交订单";
    
    self.addressDataDic = [NSMutableDictionary dictionary];
    self.dataArr = [NSMutableArray array];
    self.dataDic = [NSMutableDictionary dictionary];
    _postWayArray = [NSMutableArray array];
    
    desc_Arr = [NSMutableArray array];
    
    
    
    [self addTableviewUI];
    [self GetOrderConfirmData];
}


- (void)addTableviewUI {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height-50-NAV_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = BaseColor;
    self.tableView.separatorStyle = kSpNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"DingDanDetailLocationTableViewCell" bundle:nil]forCellReuseIdentifier:LocationIdentifier];
    [self.tableView registerClass:[DingDanDetailGoodsTableViewCell class] forCellReuseIdentifier:GoodsIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"DingDanDetailPriceTableViewCell" bundle:nil]forCellReuseIdentifier:PriceIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"DingDanDetailWordsTableViewCell" bundle:nil]forCellReuseIdentifier:WordsIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"DingDanDetailNumberTableViewCell" bundle:nil]forCellReuseIdentifier:NumberIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"DingDanPeiSongTableViewCell" bundle:nil]forCellReuseIdentifier:@"DingDanPeiSongTableViewCell"];
    
    
    
   // _cellNib = [UINib nibWithNibName:@"DingDanPeiSongTableViewCell" bundle:nil];

    [self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
    [self.view addSubview:self.tableView];
    
    CGFloat btn_weidth = 100;
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreen_Height-NAV_HEIGHT-50, kScreen_Width, 50)];
    footView.backgroundColor = [UIColor whiteColor];
    
    
    CGFloat money_weidth = 200;
    _moneyLable = [BasePublicCreatUI createLabelFrame:CGRectMake(kScreen_Width-money_weidth-btn_weidth-20, 0, money_weidth, 50) title:@"" textColor:[UIColor blackColor] textAlignment:NSTextAlignmentRight font:[UIFont systemFontOfSize:14]];
    [footView addSubview:_moneyLable];
    
    UIButton *conmitBtn = [BasePublicCreatUI createBtnFrame:CGRectMake(kScreen_Width - btn_weidth, 0, btn_weidth, CGRectGetHeight(footView.frame)) title:@"提交订单" bgImage:nil selectBgImage:nil image:nil target:self action:@selector(conmitBtnAction)];
    conmitBtn.backgroundColor = BaseBlueColor;
    conmitBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [conmitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [footView addSubview:conmitBtn];
    [self.view addSubview:footView];
    
    
}
-(void)chuliMoneyLable{
    NSString *mStr = [NSString stringWithFormat:@"%@",[_dataDic objectForKey:@"all_sell_price_s"]];
    NSString *moneyStr =[NSString stringWithFormat:@"应付 ¥%@",mStr] ;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:moneyStr];
    //设置：在0-3个单位长度内的内容显示成红色
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, mStr.length+1)];
    _moneyLable.attributedText = str;
}
-(void)cancelBtnAction{
    NSLog(@"cancelBtnAction");
}
-(void)conmitBtnAction{
    NSLog(@"conmitBtnAction");
    [self OrderCommit];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0){
        return  47 + (kScreen_Width - 40 - 30 - 40)/5.0 + 26+6 + 40;
        
    }else if (indexPath.row == 1){
        self.tableView.rowHeight = UITableViewAutomaticDimension;
        self.tableView.estimatedRowHeight = 120;
        return self.tableView.rowHeight;
    }else if (indexPath.row == 2){
        return 60;
    }else{
        return 60;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
       TiJiaoDingDanModle *modle = self.dataArr[indexPath.section];
    if (indexPath.row == 0){
        DingDanDetailGoodsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:GoodsIdentifier forIndexPath:indexPath];
        cell.delegate = self;
 
//        [cell dianjiDataArray:[NSArray arrayWithArray:self.dataArr]];
        NSArray *listArr = modle.sku_list;
        //图片
        NSMutableArray *imgArr = [NSMutableArray array];
        for (TiJiaoDingDanSkuModle *skuModle in listArr) {
            [imgArr addObject:skuModle.image];
        }
        cell.imageArray = imgArr;
        if (imgArr.count<6) {
            cell.moreImageView.hidden = YES;
        }else{
            cell.moreImageView.hidden = NO;
        }
        
        cell.titleLabel.text = [modle.shop_data objectForKey:@"shop_name"];
        NSString *all_sku_weight = modle.all_sku_weight;
        
        cell.priceLabel.text = [NSString stringWithFormat:@"¥%@ 共%@件,重量%.2fKG",modle.all_sell_price,modle.all_count_sku,all_sku_weight.integerValue/1000.0];
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else if (indexPath.row == 1){
        DingDanDetailPriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PriceIdentifier forIndexPath:indexPath];
        cell.lineView.hidden = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([modle.promotion_price isEqualToString:@"0"]) {//不优惠
            cell.titleLB.text = @"";
            cell.thirdLB.text = @"";
        }
        else {
            cell.titleLB.text = @"优惠";
            cell.thirdLB.text = [NSString stringWithFormat:@"-¥%@",modle.promotion_price];
        }
        cell.oneMoenyLB.text = [NSString stringWithFormat:@"¥%@",modle.all_sell_price_s];
        
        cell.yingFuLable.text = [NSString stringWithFormat:@"应付¥%@",modle.all_sell_price];
        cell.shiFuLable.text = [NSString stringWithFormat:@"实付¥%@",modle.all_sell_price_s];
        
        
        return cell;
    }else if (indexPath.row == 2){
        
     
        DingDanPeiSongTableViewCell *  cell = [self.tableView dequeueReusableCellWithIdentifier:@"DingDanPeiSongTableViewCell"];
       
        
        if ([modle.delivery_price isEqualToString:@"自提 ¥0"]) {
            cell.payWayLB.text =modle.delivery_price;
        }
        else if ([modle.delivery_price containsString:@"百事亨通"]) {
            cell.payWayLB.text =modle.delivery_price;
        }else {
            cell.payWayLB.text =[NSString stringWithFormat:@"百事亨通配送 %@",modle.delivery_price];
        }
      
        //postWay = modle.delivery_price;
        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapPostWay:)];
        cell.payWayLB.userInteractionEnabled = YES;
        [cell.payWayLB addGestureRecognizer:tap];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        
        return cell;
    }else if (indexPath.row == 3){
        DingDanDetailWordsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:WordsIdentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.tag = (indexPath.section + 1) *1000 ;
        [cell.rightTextFiled addTarget:self action:@selector(rightTextChangd:) forControlEvents:UIControlEventEditingChanged];
        
        return cell;
    }else{
        DingDanDetailNumberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NumberIdentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
        return cell;
        
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
        if (section == 0) {
    
            return 100;
        }else {
    return 0.01;
        }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = BaseColor;
    
    if (section == 0) {
        CGRect rect = CGRectMake(0, 0, kScreen_Width, 100);
        DingDanDetailLocationTableViewCell *cell = [[UINib nibWithNibName:LocationIdentifier bundle:nil] instantiateWithOwner:nil options:nil][0];
        
        NSString *addressStr = [NSString stringWithFormat:@"%@ %@ %@ %@",[self.addressDataDic objectForKey:@"prov"],[self.addressDataDic objectForKey:@"city"],[self.addressDataDic objectForKey:@"area"],[self.addressDataDic objectForKey:@"address"]];
        NSString *nameAndTel = [NSString stringWithFormat:@"%@ %@",[self.addressDataDic objectForKey:@"full_name"],[self.addressDataDic objectForKey:@"tel"]];
        
        if (self.addressDataDic.count) {
            cell.locationLable.text = addressStr;
            cell.nameLable.text = nameAndTel;
            
        }else{
            cell.addLocationBtn.hidden = NO;
            cell.locationImgView.hidden = YES;
            cell.nameLable.hidden = YES;
            cell.locationLable.hidden = YES;
            cell.rightBtn.hidden = YES;
        }
        
        
        cell.frame = rect;
        UIView * view = [[UIView alloc] initWithFrame:rect];
        [view addSubview:cell];
        view.backgroundColor = [UIColor whiteColor];
        [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ChooseLocation:)]];
        [headerView addSubview:view];
    }
    
    
    
    return headerView;
}

-(void)ChooseLocation:(UITapGestureRecognizer *)tap{
    
    
    // 添加地址
    MyAddressViewController *vc = [[MyAddressViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footview = [[UIView alloc] init];
    footview.backgroundColor = BaseColor;
    
    return footview;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row ==0) {
        
        GoodsMingXiViewController *vc = [[GoodsMingXiViewController alloc] init];
        vc.goodsArray = [NSArray arrayWithArray:_dataArr];
        vc.typeStr = 2;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
    if (indexPath.row ==2) {
 
    }
}

- (void)handleTapPostWay:(UITapGestureRecognizer *)tap {
    DingDanPeiSongTableViewCell *cell = (DingDanPeiSongTableViewCell *)[[tap.view superview] superview];
    NSIndexPath *indePath = [self.tableView indexPathForCell:cell];
    indepathSection = indePath.section;
    indepathrow = indePath.row;
    

    NSString *str = [NSString stringWithFormat:@"百事亨通配送 %@",_postWayArray[indePath.section]];
    NSArray *array = @[@"自提 ¥0",str];
    if (_picker) {
        [_picker removeFromSuperview];
    }
    
   _picker  = [[HQPickerView alloc]initWithFrame:self.view.bounds];
    _picker.delegate = self ;
    
    _picker.customArr = array;
    [self.view addSubview:_picker];
    
 
}
- (void)pickerView:(UIPickerView *)pickerView didSelectText:(NSString *)text {
    
    
    TiJiaoDingDanModle *modle = self.dataArr[indepathSection];
    modle.delivery_price = text;
    //一个section刷新
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:indepathSection];
    [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    
}




#pragma mark ------------- 商品明细 -----------
-(void)DingDanDetailGoodsImgCellClicked{
    GoodsMingXiViewController *vc = [[GoodsMingXiViewController alloc] init];
    vc.goodsArray = [NSArray arrayWithArray:_dataArr];
    vc.typeStr = 2;
    [[BasePublicClass getCurrentVC].navigationController pushViewController:vc animated:YES];
    
}

#pragma mark -------------------  留言备注
-(void)rightTextChangd:(UITextView *)textF{
    
    NSInteger t = [[textF superview] superview].tag/1000;
    
    
    
    [desc_Arr replaceObjectAtIndex:t-1 withObject:textF.text];
    NSLog(@"%ld  %@", t,textF.text);
    
    
}





#pragma mark －＝－＝－－＝－＝－＝－获取订单详情接口－＝－－＝＝
//http://bs.m0571.com/mobileapi/public/baishi/?service=Shop_Order.OrderConfirm&userid=11&sku_id=1&buy_type=cart&actoken=8bf3a36d1af1e4d8054da405c4696b97.900.1504682370
// 获取订单详情
-(void)GetOrderConfirmData{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic;
    if (_buy_num.length>0) {
        parameDic = @{@"userid":saveDic[@"userid"],@"sku_id":_sku_id,@"buy_type":_buy_type,@"buy_num":_buy_num,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    }else{
        parameDic = @{@"userid":saveDic[@"userid"],@"sku_id":_sku_id,@"buy_type":_buy_type,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    }
    
    
    [HttpRequest postWithURLString:POST(Shop_OrderConfirm) parameters:parameDic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        _dataDic = [responseObject objectForKey:@"data"];
        [self chuliMoneyLable];
        
        if ([[responseObject objectForKey:@"ret"] integerValue] == 200) {
            
            NSArray *listarr = [[responseObject objectForKey:@"data"] objectForKey:@"list"];
        
            self.dataArr = [TiJiaoDingDanModle mj_objectArrayWithKeyValuesArray:listarr];
            
            
            //先把运费保存一下
            if (_postWayArray ) {
                [_postWayArray removeAllObjects];
            }
            for (TiJiaoDingDanModle *model  in self.dataArr) {
                [_postWayArray addObject:model.delivery_price];
            }

            self.addressDataDic = [[responseObject objectForKey:@"data"] objectForKey:@"address_data"];
            
          
            
            
            
        }else{
            [MBProgressHUD showText:[responseObject objectForKey:@"msg"]];
        }
        
        for (NSInteger i = 0; i<self.dataArr.count; i++) {
            [desc_Arr addObject:@"暂无备注留言"];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
}



#pragma mark －＝－－＝提交订单按钮的点击事件

// 提交订单
-(void)OrderCommit{
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
   
    
    //备注
     NSMutableArray *liuYArray = [NSMutableArray array];
   
    for (NSInteger i = 0; i<desc_Arr.count; i++) {
        NSString *desStr = desc_Arr[i];
        TiJiaoDingDanModle *model = self.dataArr[i];
        
        if (desStr.length) {
             NSString *tempStr = [NSString stringWithFormat:@"%@|%@",model.shop_id,desStr];
            [liuYArray addObject:tempStr];
        }
        
        
        
    }
    NSArray *TaTitleA = [NSArray arrayWithArray:liuYArray];
    NSString *strTempStr =[TaTitleA componentsJoinedByString:@","];//多个商铺拼接留言
    
    
    
    
    //遍历更改过的对象，判断是否自提，然后根据后台规则存入数组
    NSMutableArray *dataIDA = [NSMutableArray array];
    for (TiJiaoDingDanModle *model in self.dataArr) {
        NSLog(@"%@",model.delivery_price);
        NSString *spc;
        if ([model.delivery_price containsString:@"自提"]) {
           spc = [NSString stringWithFormat:@"%@|%@",model.shop_id,@"1"];
        }else {
            spc = [NSString stringWithFormat:@"%@|%@",model.shop_id,@"0"];
        }
        [dataIDA addObject:spc];
    }
    
    NSArray *tempA = [NSArray arrayWithArray:dataIDA];
    NSString *tIDstring = [tempA componentsJoinedByString:@","];//店铺对应的收货方式
    
    
    
    NSMutableDictionary *parameDic = [NSMutableDictionary dictionary];
    [parameDic setObject:saveDic[@"userid"] forKey:@"userid"];
    [parameDic setObject:_sku_id forKey:@"sku_id"];
    [parameDic setObject:_buy_type forKey:@"buy_type"];
    [parameDic setObject:[Md5Apiway getMD5data:saveDic[@"userid"]] forKey:@"actoken"];
    [parameDic setObject:self.addressDataDic[@"id"] forKey:@"address_id"];
    [parameDic setObject:tIDstring forKey:@"is_own"];

    
    if (_buy_num.length>0) {// _buy_num购买数量,购物车时不需要
        [parameDic setObject:_buy_num forKey:@"buy_num"];
    }
    
    if (strTempStr.length) {
        [parameDic setObject:strTempStr forKey:@"desc_str"];
    }
    
    
    
    
    
    
//desc_str 备注,例：店铺ID|备注内容（注意：|为分割符）,多个逗号分割

    [HttpRequest postWithURLString:POST(Shop_OrderCommit) parameters:parameDic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        if ([[responseObject objectForKey:@"ret"] integerValue] == 200) {
            PayForViewController *vc = [[PayForViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            
            
            
            vc.orderIdStr =responseObject[@"data"][@"order_no"];
            vc.payMoenyStr =responseObject[@"data"][@"all_order_price"];
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refshIngShopCar" object:nil];
            
        }else{
            [MBProgressHUD showText:[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"msg"]]];
        }
        
        
    } failure:^(NSError *error) {
        
    }];
    
}


@end
